<?php

namespace app\index\controller;

use think\exception\ValidateException;
use app\model\Wxmp;
use app\model\Openid;
use function Qiniu\entry;

class WechatmpController extends Base
{

	public function wechat()
	{
		$backurl = input('param.backurl');

		$app =  Wxmp::make();
		$oauth = $app->oauth;

		//回调地址
		$callback_url = gethost() . $_SERVER["SCRIPT_NAME"] . '/index/wechatmp/wechatres?i=' . weid() . '&xmtoken=' . $this->getToken() . '&uid=' . input('param.uid') . '&backurl=' . urlencode($backurl);
		$response = $oauth->scopes(['snsapi_base'])->redirect($callback_url);

		// 将响应输出
		$response->send();
	}
	public function wechatuserinfo()
	{
		$backurl = input('param.backurl');

		$app =  Wxmp::make();
		$oauth = $app->oauth;

		//回调地址
		$callback_url = gethost() . $_SERVER["SCRIPT_NAME"] . '/index/wechatmp/wechatres?i=' . weid() . '&xmtoken=' . $this->getToken() . '&uid=' . input('param.uid') . '&backurl=' . urlencode($backurl);
		$response = $oauth->scopes(['snsapi_userinfo'])->redirect($callback_url);

		// 将响应输出
		$response->send();
	}

	public function wechatres()
	{

		$app = Wxmp::make();
		$oauth = $app->oauth;

		// 获取 OAuth 授权结果用户信息
		$user = $oauth->user();
		//print_r($user);}
		$uid = input('get.uid');
		$xmtoken = input('get.xmtoken');
		$openid = $user->getId();
		if (!empty($uid)) {
			if (!Openid::where(['weid' => weid(), 'ptype' => 'mp', 'uid' => $uid, 'openid' => $openid])->find()) {
				Openid::create([
					'weid' => weid(),
					'ptype' => 'mp',
					'uid' => $uid,
					'openid' => $openid
				]);
			}
		}
		$data = $this->userInfo;

		$data['ptype'] = 'mp';
		$data['openid'] = $openid;
		$data['nickname'] = $user->getNickname();
		$data['avatar'] =  $user->getAvatar();
		$data['weid'] = weid();
		$this->setToken($data, $xmtoken);
		$backurl = input('get.backurl');

		return redirect($backurl);
	}

	public function getopenid()
	{
		$backurl = input('param.backurl');

		$app =  Wxmp::make();
		$oauth = $app->oauth;

		//回调地址
		$callback_url = gethost() . $_SERVER["SCRIPT_NAME"] . '/index/wechatmp/getopenidres?i=' . weid() . '&xmtoken=' . $this->getToken() . '&uid=' . input('param.uid') . '&backurl=' . urlencode($backurl);
		$response = $oauth->scopes(['snsapi_base'])->redirect($callback_url);

		// 将响应输出
		$response->send();
	}
	public function getopenidres()
	{

		$app = Wxmp::make();
		$oauth = $app->oauth;

		// 获取 OAuth 授权结果用户信息
		$user = $oauth->user();
		$openid = $user->getId();

		$backurl = input('get.backurl');

		$backurl = str_replace('#/', '', $backurl);
		if (strpos($backurl, '?') !== false) {
			$backurl = $backurl . '&openid=' . $openid;
		} else {
			$backurl = $backurl . '?openid=' . $openid;
		}

		return redirect($backurl);
	}
}
